// pages/introduce/introduce.js
const App = getApp()
var utils = require('../../utils/classDict');
const computedBehavior = require('miniprogram-computed').behavior

Page({
  behaviors: [computedBehavior],
  data: {
    agree: false,
    detail: {},
    id: "",
    showAll: false,
    classDict: utils.classDict,
    form: {
      userName: '', //学生姓名
      soundCourseType: '', //声部类型
      gradeLevel: 0, //年级1~9
      className: 0, //班级
      gender: "", //性别
      homeCode: "", //家庭编号
    },
    clsList: [],
    soundCourseType: "",
    disabled: false,
    currentStudent: "",
    currentStudentID: "",
    goodsInfoList: [], //乐器列表
    marketPriceRmbs: 0, // 市场价
    groupPriceRmbs: 0, // 团购价
    soundCourseTypeName: '', //声部名称
    myStudentList: [],
    allStudentList: [], // 已有学生列表
    studentBoxStatus: false,
    success: false, //报名成功状态
    payStudentList: [], //已缴费学生
    noPaystudentList: []
  },
  computed: {
    className(data) {
      let name = utils.classDict[0][data.clsList[0]]?.name
      console.log(data.clsList)
      return name
    },
    classIndex(data) {
      let name = utils.classDict[1][data.clsList[1]]?.name
      return name
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!options.id) return
    this.getDetail(options.id)
  },
  getDetail: async function (id) {
    // 获取团课
    let data = await App.$axios.request({
      url: `/parent/curriculum/bigInfo`,
      data: {
        id
      },
      method: 'GET',
      loading: true,
    })
    if (!data) return
    this.setData({
      id: id,
      detail: data,
      disabled: data.curriculumStatus != 1,
    })
    if (data.status == 2) {
      data.studentList.map(item => {
        item.gradeLevel = item.gradeLevel - 1
        item.className = item.className - 1
        return item
      })
      let list = data.studentList.filter(item => {
        return item.registrationStatus != 2
      })
      let payList = data.studentList.filter(item => {
        return item.registrationStatus == 2
      })
      this.setData({
        noPaystudentList: list,
        payStudentList: payList
      })
      if (list.length == 1) {
        this.changeStudent({
          detail: {
            value: 0
          }
        })
      }
    }
    if (data.status == 1) {
      this.setData({
        myStudentList: data.studentList
      })
      this.getStudentList()
    }
  },
  changeInfoBox() {
    this.setData({
      showAll: !this.data.showAll
    })
  },
  checkboxChange(item) {
    // 同意框
    this.setData({
      agree: !item.currentTarget.dataset.agree
    })
  },
  pay: async function () {
    // 立即支付
    let detail = this.data.detail
    if (!this.data.agree) {
      wx.showToast({
        title: "请先确认须知！",
        icon: "error",
        duration: 2000
      })
      return
    }
    if (detail.curriculumStatus == 0 || detail.curriculumStatus == 4) {
      // 课程状态curriculum_status（0:未开始，1:报名中；2:缴费中；3:成团；4:关闭）
      wx.showToast({
        title: `${detail.curriculumStatus == 0?'未开始':'已结束'},请与客服确认`,
        icon: "none",
        duration: 2000
      })
      return
    }
    if (detail.curriculumStatus == 2) {
      // 缴费中逻辑
      if (!this.data.form.userName) {
        wx.showToast({
          title: '请先选择学生',
          icon: 'none'
        })
        return
      }
      this.createOrder()
    } else {
      // 报名逻辑
      // if (this.data.success) return this.reNewData()
      if (this.data.clsList.length < 1) {
        wx.showToast({
          title: '班级未选择',
          icon: 'error'
        })
        return
      }
      let data = await App.$axios.request({
        url: "/parent/curriculum/studentRegistration",
        data: {
          curriculumId: this.data.detail.id,
          ...this.data.form
        },
        method: 'POST',
        loading: true,
      })
      if (data === true) {
        this.setData({
          success: true
        })
        wx.showToast({
          title: `${this.data.form.userName}报名${this.data.detail.curriculumName}成功！`,
          icon: "none"
        })
        this.reNewData()
        this.getDetail(this.data.id)
      }
    }
  },
  curriculumBigSoundListChange(item) {
    // 声部修改
    let index = item.detail.value
    this.setData({
      'form.soundCourseType': this.data.detail.curriculumBigSoundList[index].type,
      soundCourseType: index
    })
  },
  sexChange(item) {
    // 性别修改
    this.setData({
      'form.gender': parseInt(item.detail.value)
    })
  },
  changeInput(item) {
    // 姓名修改
    this.setData({
      'form.userName': item.detail.value
    })
  },
  classChange(item) {
    // 班级修改
    let cls = JSON.parse(JSON.stringify(item.detail.value))
    let classDict = this.data.classDict
    this.setData({
      'form.gradeLevel': classDict[0][cls[0]].id,
      'form.className': classDict[1][cls[1]].id,
      clsList: [cls[0], cls[1]]
    })
  },
  async changeStudent(e) {
    // 选择缴费学生
    let index = parseInt(e.detail.value)
    let item = this.data.noPaystudentList[index]
    this.studentDataFormart(item)
  },
  studentDataFormart(data = {}) {
    let marketPriceRmbs = 0 // 市场价
    let groupPriceRmbs = 0 // 团购价
    if (data.goodsInfoVOList.length) {
      data.goodsInfoVOList.forEach(e => {
        e.checkd = true
        marketPriceRmbs = marketPriceRmbs + e.marketPriceRmb
        groupPriceRmbs = groupPriceRmbs + e.groupPriceRmb
      })
    }
    this.setData({
      marketPriceRmbs: marketPriceRmbs,
      groupPriceRmbs: groupPriceRmbs,
      currentStudent: data.userName,
      currentStudentID: data.id,
      clsList: [data.gradeLevel, data.className],
      form: {
        userName: data.userName, //学生姓名
        soundCourseType: data.soundCourseType, //声部类型
        gradeLevel: data.gradeLevel, //年级1~9
        className: data.className, //班级
        gender: data.gender, //性别
        // homeCode: data.homeCode, //家庭编号
      },
      goodsInfoList: data.goodsInfoVOList,
      soundCourseTypeName: data.soundCourseTypeName //声部名称
    })
  },
  changeBuyStatus(e) {
    // 选择乐器
    let item = e.currentTarget.dataset.index
    // let itemCheck = 'goodsInfoList[' + item + '].checkd'
    let goodsInfoList = JSON.parse(JSON.stringify(this.data.goodsInfoList))
    goodsInfoList[item].checkd = !goodsInfoList[item].checkd
    let marketPriceRmbs = 0 // 市场价
    let groupPriceRmbs = 0 // 团购价
    goodsInfoList.forEach(e => {
      if (e.checkd) {
        marketPriceRmbs = marketPriceRmbs + e.marketPriceRmb
        groupPriceRmbs = groupPriceRmbs + e.groupPriceRmb
      }
    })
    let checkList = goodsInfoList.filter(e => {
      return e.checkd == true
    })
    if (checkList.length < 1) {
      wx.showToast({
        title: '至少选择一种乐器',
        icon: "none"
      })
      return
    }
    this.setData({
      // [itemCheck]: !this.data.goodsInfoList[item].checkd,
      goodsInfoList: goodsInfoList,
      marketPriceRmbs: marketPriceRmbs,
      groupPriceRmbs: groupPriceRmbs
    })
  },
  async createOrder() {
    // 创建订单
    let goodsIdList = []
    if (this.data.goodsInfoList.length) {
      this.data.goodsInfoList.forEach(e => {
        if (e.checkd) {
          goodsIdList.push(e.id)
        }
      })
    }
    let data = await App.$axios.request({
      url: `/parent/order/curriculum/buyOrder`,
      data: {
        dataId: this.data.id,
        studentUserId: this.data.currentStudentID,
        dataType: 3,
        goodsIdList: goodsIdList
      },
      method: 'POST',
      loading: true,
    })
    if (data && data.orderNum) {
      wx.redirectTo({
        url: `/pages/pay/pay?orderNum=${data.orderNum}&nonceStr=${data.nonce_str}&timeStamp=${data.timeStamp}&timeStamp=${data.timeStamp}&signType=${data.signType}&package=${data.prepay_id}&paySign=${data.sign}`,
      })
    }
  },
  changeStudentBoxStatus() {
    this.setData({
      studentBoxStatus: !this.data.studentBoxStatus
    })
  },
  async getStudentList() {
    // 学生查询
    let data = await App.$axios.request({
      url: `/parent/myCurriculum/student`,
      method: 'GET',
      loading: true,
      data: {
        // name: "皮卡卡"
      },
    })
    if (data) {
      data.forEach(e => {
        e.class = `${e.gradeLevel?e.gradeLevel+'年级':''}${e.className?e.className+'班':''}`
      })
      this.setData({
        allStudentList: data
      })
    }
  },
  selectStudent(e) {
    // 快捷选择学生
    if (!e.detail.value) return
    let index = parseInt(e.detail.value)
    console.log(this.data.allStudentList)
    let item = this.data.allStudentList[index]
    console.log(item)
    this.setData({
      clsList: [item.gradeLevel - 1, item.className - 1],
      form: {
        userName: item.userName, //学生姓名
        soundCourseType: '', //声部类型
        gradeLevel: item.gradeLevel, //年级1~9
        className: 0, //班级
        gender: item.gender, //性别
        homeCode: item.homeCode, //家庭编号
      }
    })
  },
  reNewData() {
    // 重置信息
    this.setData({
      agree: false,
      // success: false,
      clsList: [],
      form: {
        userName: '', //学生姓名
        soundCourseType: '', //声部类型
        gradeLevel: 0, //年级1~9
        className: 0, //班级
        gender: "", //性别
        homeCode: "", //家庭编号
      },
    })
  }
})